﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;
    import Portfolio = Sustainalytics.Portfolio;
    import EsgRatingsAdmin = Sustainalytics.EsgRatings.Admin;
    import LRTM = Sustainalytics.LRTM;



    export enum PortfolioUniversesType {
        MyPortfolios = 0,

        SharedPortfolios,

        Universe,

        SystemPortfolio
    }

    export class EditFilterController {
        public currentFilter: FilterDto;
        public currentFilterCriteria: FilterCriteriaDto[];

        public regionPersistedItems: CriteriaGenericDto[];
        public peerGroupPersistedItems: CriteriaGenericDto[];
        public countryPersistedItems: CriteriaGenericDto[];
        public companyTypePersistedItems: CriteriaGenericDto[];
        public portfoliosUniversesMixItems: Portfolio.PortfolioUniverseMixDto[];

        public allPortfoliosUniverses: any[] = [];


        public weightMatrices: EsgRatingsAdmin.WeightMatrix[] = [];
        public referenceUniverses: EsgRatingsAdmin.IReferenceUniverse[];
        public comparativeGroups: { name: string; value: string; }[];
        public companyTypes: { name: string; value: string; }[];
        public researchTypes: { name: string; value: string; }[];
        public exportTypes: { name: string; value: string; }[];
        public refreshOutput: boolean;

        public portfoliosUniversePlaceHolder: string;
        public peerGroupPlaceHolder: string;
        public regionPlaceHolder: string;
        public countryPlaceHolder: string;
        public companyTypePlaceHolder: string; 
                
        // specifies whether current controller is in loading state
        public isLoading: boolean;
        private accountId: string;
        private userId: string;
        public accountTier: number;

        public orderByAsc: boolean;
        public orderByCol: string;

        public resultOutputPaged: Common.PagedList<ResultOutput>;

        public resultOutputFilter: ResultOutputFilter;
        public resultOutputOrderBy: string;
        public resultOutputOrderByAscending: boolean;
        private $routeParams: any;

        public  hasPortfolioPermision: boolean;
        public accountUniverses: Universe[];
        //public accountUniverseSelected: (universeId: number) => void;
        public accountUniverseId: number;      

        //public portfolios: any;
        //public currentPortfolio: Portfolio.PortfolioUniverseMixDto;
        //public currentUniverse: Portfolio.PortfolioUniverseMixDto;
        //public currentPortfolioOrUniverse: Portfolio.PortfolioUniverseMixDto;
        public currentPeerGroup: any;
        public currentRegion: any;
        public currentCountry: any;
        public currentCompanyType: any;
               
        public accountPortfolioOrUniverseId: number;
        //public portfolioId: string;
        //public portfolioName: string;

        public crtPeerGroupId: string;
        public crtPeerGroupName: string;

        public regionId: string;
        public regionName: string;

        public countryId: string;
        public countryName: string;

        public companyTypeId: number;     

        public weightMatrixId: string;
        public referenceUniverseId: string;
        public comparativeGroup: string;
        public companyTypePublicOrPrivate: string;
        public researchType: string;
        public exportType: string;

        public newNameFilter: string;
        public isRenamingFilterName: boolean;

        public isAdmin: boolean; //shows whether the module is used in CI or AI
        public operationsPopupId: string = "";

        public isSettingsCollapsed: boolean = false;
        public isSelectedCriteriaCollapsed: boolean = false;
        public isPreviewCollapsed: boolean = false;

        public showResults: boolean;
        public showNoData: boolean;

        public companyTypeModel: any[] = [];
        public companyTypeOptions: any[] = [];
        public companyTypeSettings: any;
        public companyTypeEvents: any;
        public companyTypeTranslationTexts: any;

        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private RoutingService: Routing.IRoutingService,
            private FilterService: IFilterService,
            private FilterCriteriaService: IFilterCriteriaService,
            private screeningToolFactory: IScreeningToolFactory,
            private PortfolioService: Portfolio.IPortfolioService,
            private PortfolioSearchService: Portfolio.PortfolioSearchService,
            private notificationFactory: Common.INotificationFactory,
            private WeightMatricesService: EsgRatingsAdmin.IWeightMatricesService,
            private ReferenceUniversesService: EsgRatingsAdmin.IReferenceUniversesService,
            private staticObjects: Common.IStaticObjects,
            private $modal: Common.IModal,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {
            
            var ctx = this;
            $scope['filterEdit'] = ctx;

            ctx.orderByAsc = true;
            ctx.orderByCol = "NameLowercase";
            ctx.$rootScope['loading'] = true;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }

            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.accountTier = ctx.$rootScope['userInfo'].accountTier;
            //ctx.esgProfileId = ctx.$rootScope['userInfo'].esgProfileId;

            ctx.isRenamingFilterName = false;

            ctx.$routeParams = ctx.RoutingService.getRouteParams();
            ctx.isAdmin = $location.absUrl().indexOf('/admin/') > 0;
            ctx.refreshOutput = false;

            //ctx.currentPortfolio = undefined;
            //ctx.currentUniverse = undefined;
            //ctx.currentPortfolioOrUniverse = undefined;
            ctx.currentPeerGroup = undefined;
            ctx.currentRegion = undefined;
            ctx.currentCountry = undefined;
            ctx.currentCompanyType = undefined;

            ctx.hasPortfolioPermision = this.PortfolioService.hasPermision();

            // init result output filter
            ctx.resultOutputFilter = new ResultOutputFilter();
            ctx.resultOutputFilter.isValidEnabled = true;
            ctx.resultOutputFilter.isNotValidEnabled = true;
            ctx.resultOutputFilter.isNAEnabled = true;
            ctx.resultOutputFilter.isValid = null; // 4
            ctx.resultOutputOrderBy = "CompanyNameLowerCase";
            ctx.resultOutputOrderByAscending = true;



            ctx.companyTypeOptions = CompanyTypeOptions;

            ctx.companyTypeSettings = {
                smartButtonMaxItems: 3,
                showCheckAll: false,
                showUncheckAll: false,
                smartButtonTextConverter: function (itemText, originalItem) {
                    return itemText;
                }              
            };

            ctx.companyTypeEvents = {
                onMultiSelectBlur: function () {                    
                    ctx.showResults = false;

                    var selectedTypes = 0;
                    ctx.companyTypeModel.forEach(item => selectedTypes |= item.id);

                    var companyTypeSelection = (selectedTypes == 0) ? null : selectedTypes;

                    if (ctx.currentCompanyType != companyTypeSelection) {                        
                        ctx.currentCompanyType = companyTypeSelection;
                        ctx.currentFilter.companyType = companyTypeSelection;                        

                        ctx.saveFilter().then(() => {
                        });
                    }                   
                }
            };

            ctx.companyTypeTranslationTexts = { buttonDefaultText: "Select Company Type" };
            
            //Load first Filter Settings from DBase collection items relevant for all drop-downs...
            ctx.$rootScope['loading'] = true;
            ctx.loadFilter().then(() => {

                this.$scope.$watch(() => this.resultOutputOrderBy,
                (newValue: string, oldValue: string) => {
                    if (oldValue != undefined) {
                        if (oldValue !== newValue) {
                            this.getResultOutput();
                        }
                    }
                });

                this.$scope.$watch(() => this.resultOutputOrderByAscending,
                (newValue: string, oldValue: string) => {
                    if (oldValue != undefined) {
                        if (oldValue !== newValue) {
                            this.getResultOutput();
                        }
                    }
                });

                // if filter (the below fields are used only for a filter)
                if (ctx.currentFilter.targetType === 0) {
                    this.$scope.$watch(() => this.resultOutputFilter.isValid,
                    (newValue: string, oldValue: string) => {
                        if (oldValue !== newValue) {
                            this.getResultOutput(1);
                        }
                    });

                    this.$scope.$watch(() => this.resultOutputFilter.isValidEnabled,
                    (newValue: string, oldValue: string) => {
                        if (oldValue !== newValue) {
                            this.computeResultOutputFilterIsValid();
                        }
                    });

                    this.$scope.$watch(() => this.resultOutputFilter.isNotValidEnabled,
                    (newValue: string, oldValue: string) => {
                        if (oldValue !== newValue) {
                            this.computeResultOutputFilterIsValid();
                        }
                    });

                    this.$scope.$watch(() => this.resultOutputFilter.isNAEnabled,
                    (newValue: string, oldValue: string) => {
                        if (oldValue !== newValue) {
                            this.computeResultOutputFilterIsValid();
                        }
                    });
                }
                ////Set initial values for filters as present in the Database - this should be done only after editedFilter loads
                //ctx.setInitialLoadedFilterSettings(ctx.currentFilter);
            
                //ctx.runCurrentCriteria();
                ctx.FilterCriteriaService.addFilterCriteriaToFilter(ctx.currentFilter.id,[]).then(a => {
                    ctx.getResultOutput(0); 
                });
                  
                
                ctx.loadFilterSettingsCollections().then(() => {
                    //Set initial values for filters as present in the Database - this should be done only after editedFilter loads
                    ctx.setInitialLoadedFilterSettings(ctx.currentFilter);
                });


                var eventCategory = "";
                var eventAction = "";
                if (ctx.currentFilter.targetType === TargetType.Report) {
                    eventCategory = 'Reporting tool - custom reports';
                    eventAction = 'OnscreenCustomReport';
                }
                else {
                    eventCategory = 'Screening tool - custom filters';
                    eventAction = 'OnscreenCustomFilter';
                }

                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId,
                    'cookieDomain': 'none',
                    'name': 'globalAccess'
                });

                ga('globalAccess.set', 'dimension1', ctx.userId);

                var dateNow = new Date();
                var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                var gaObject: any = {
                    Date: dateNowString,
                    AccountId: ctx.accountId,
                    UserId: ctx.userId
                };

                ga('globalAccess.send', {
                    'hitType': 'event',
                    'eventCategory': eventCategory,
                    'eventAction': eventAction,
                    'eventLabel': JSON.stringify(gaObject)
                });
            });

            ctx['sortableOptions'] = {
                //'ui-floating': false,
                stop: (event, ui) => {
                    ctx.updateFilterCriteriaOrder();
                }
            };

            ctx.handlePagerChanged();
        }

        //#region FilterSettings

        private setSelectedItem = function (): any[] {
            var ctx = this;
            var allPortfoliosTemp: any = {};
            ctx.allPortfoliosUniverses.forEach(item => {
                if (item.children != undefined) { 
                    item.children.forEach(child => {

                        if (child.id == ctx.currentFilter.selectedPortfolioUniverse.id) {
                            child.selected = true;
                        }

                    });
                }
            });


            return allPortfoliosTemp;
        };


       

        private  formatDataForMultiSelect = (data): any[] => {
              var allPortfoliosTemp: any[] = [];

              var myPortfolios = {
                  id: "00000000-0000-0000-0000-000000000000",
                  name: "My portfolios",
                  type:PortfolioUniversesType.MyPortfolios,
                  children: new Array()
              };

              var universes = {
                  id: "00000000-0000-0000-0000-000000000001",
                  name: "Universes",
                  type: PortfolioUniversesType.Universe,
                  children: new Array()
              };
              var systemPortfolios = {
                  id: "00000000-0000-0000-0000-000000000002",
                  name: "System portfolios",
                  type: PortfolioUniversesType.SystemPortfolio,
                  children: new Array()
              };
              var sharedPortfolios = {
                  id: "00000000-0000-0000-0000-000000000003",
                  name: "Shared portfolios",
                  type: PortfolioUniversesType.SharedPortfolios,
                  children: new Array()
              } ;

              allPortfoliosTemp.push(myPortfolios);
            
              allPortfoliosTemp.push(sharedPortfolios);

              allPortfoliosTemp.push(systemPortfolios);

              allPortfoliosTemp.push(universes);

              data.forEach(item => {

                  var parent = allPortfoliosTemp.filter(parentItem => (parentItem.type===item["type"]));
                  parent[0].children.push(item);
              });
              return allPortfoliosTemp;
          };
        
        private loadFilterSettingsCollections() : ng.IPromise<any> {
            var ctx = this;

            var def = ctx.$q.defer();

            //ctx.$rootScope['loading'] = true;

            //"undefined" value it's the parameter value because  that's the way SearchBoxController calls search from UI event - it's the way to bring them all
            var portfoliosUniversesGetPromise: ng.IHttpPromise<any[]> = ctx.PortfolioSearchService.SearchScreeningToolPortfoliosAndUniversesMix(undefined, 0, 999);

            var defaultMatrix = {
                id: "00000000-0000-0000-0000-000000000000",
                name: "Default Weight Matrix",
                accountId: "00000000-0000-0000-0000-000000000000",
                isSelectedInActiveProfile: false,
                markedForDeletionOn: null,
                processedDeletionOn: null
            };

            ctx.weightMatrices.push(defaultMatrix);

            var peerGroupGetPromise: ng.IHttpPromise<CriteriaGenericDto[]> = ctx.screeningToolFactory.SearchByCriteriaId("Peer Group", undefined, 0, 999);
            var regionsGetPromise: ng.IHttpPromise<CriteriaGenericDto[]> = ctx.screeningToolFactory.SearchByCriteriaId("Region", undefined, 0, 999);
            var countryGetPromise: ng.IHttpPromise<CriteriaGenericDto[]> = ctx.screeningToolFactory.SearchByCriteriaId("Country", undefined, 0, 999);
            var companyTypeGetPromise: ng.IHttpPromise<CriteriaGenericDto[]> = ctx.screeningToolFactory.SearchByCriteriaId("Company type", undefined, 0, 999);

            var accountWeightMatricesPromise = ctx.WeightMatricesService.listWeightMatricesByAccountId(ctx.accountId, false);
            var refUnivPromise = ctx.ReferenceUniversesService.getReferenceUniverses();

            var allPromises = ctx.$q.all(
                [
                    portfoliosUniversesGetPromise,
                    peerGroupGetPromise,
                    regionsGetPromise,
                    countryGetPromise,
                    companyTypeGetPromise,
                    accountWeightMatricesPromise,
                    refUnivPromise
                ])
                    .then(resultsArray => {
                   
                    this.portfoliosUniversesMixItems = resultsArray[0].data;
              
                    this.allPortfoliosUniverses = this.formatDataForMultiSelect(resultsArray[0].data);               
                    this.peerGroupPersistedItems = resultsArray[1].data;
                    this.regionPersistedItems = resultsArray[2].data;
                    this.countryPersistedItems = resultsArray[3].data;
                    this.companyTypePersistedItems = resultsArray[4].data;

                    if (resultsArray[5]) { //weight matrices
                        for (var i = 0; i < resultsArray[5].length; i++) {
                            ctx.weightMatrices.push(resultsArray[5][i]);
                        }
                    }

                    //reference universe
                    ctx.referenceUniverses = resultsArray[6];

                    //for Report
                    this.comparativeGroups =
                    [
                        { name: "Peer Group", value: ComparativeGroupEnum.PeerGroup.toString() },
                        { name: "Industry Group", value: ComparativeGroupEnum.IndustryGroup.toString() }
                    ]; 

                    this.companyTypes =
                    [
                        { name: "No", value: "1" },
                        { name: "Yes", value: "2" }
                    ];

                    this.researchTypes =
                    [
                        { name: "No", value: "1" },
                        { name: "Yes", value: "2" }
                    ];

                    this.exportTypes =
                    [
                        { name: "Excel", value: ExportType.Excel.toString() },
                        { name: "CSV", value: ExportType.CSV.toString() }
                    ];
                    //

                    def.resolve();

                }, (errorReason => { console.log(errorReason); def.reject(errorReason); }) )
            .finally(() => {
                  
                });

            return def.promise;
        }
        
        public deleteFilterCriteriaById(filterCriteriaId: string) {
            var ctx = this;
            ctx.$rootScope['loading'] = true;
            var promise = ctx.FilterCriteriaService.deleteFilterCriteriaById(ctx.currentFilter.id, filterCriteriaId);
            promise
                .then(
                () => {
                    ctx.showResults = false;
                    ctx.getResultOutput(1);
                });

            return promise;
        }
        
        public deleteFilterCriteriaGroup(filterCriteriaId: string, filterGroupId: string) {
            var ctx = this;
            var promise = ctx.FilterCriteriaService.deleteFilterCriteriaGroup(ctx.currentFilter.id, filterCriteriaId, filterGroupId);
            promise.then(() => {
                //this.runCriteria(this.currentFilter.id);
                ctx.FilterCriteriaService.addFilterCriteriaToFilter(ctx.currentFilter.id, []).then(a => {
                    ctx.showResults = false;
                    ctx.getResultOutput(0);
                });
            });
            return promise;
        }         

        private setInitialLoadedFilterSettings(filter: FilterDto) {
            var ctx = this;
            if (filter == null)
                        return;

            var selectItemTemp: any;

            if (filter.portfolioId != null && filter.portfolioId != undefined) {
                selectItemTemp = { "id": filter.portfolioId };
            } else {

                if (filter.universeId != null && filter.universeId != undefined && filter.universeId !== 0) {
                    selectItemTemp = { "id": filter.universeId };
                } else {
                    ctx.portfoliosUniversePlaceHolder = "Search Portfolio or Universe";
                }
            }
            if (selectItemTemp != undefined) {
                ctx.currentFilter.selectedPortfolioUniverse = selectItemTemp;
                ctx.setSelectedItem();
            }


            if (filter.peerGroup != null && filter.peerGroup != undefined) {               
                var peerGroupName = ctx.matchIdStringToNameForDataCollection(filter.peerGroup, ctx.peerGroupPersistedItems);
                ctx.currentPeerGroup = ctx.matchCurrentItem(filter.peerGroup, ctx.peerGroupPersistedItems);
                  
            }
            else {
                ctx.peerGroupPlaceHolder = "Search Peer Group";
            }


            if (filter.region != null && filter.region != undefined) {                
                var regionName = ctx.matchIdStringToNameForDataCollection(filter.region, ctx.regionPersistedItems);
                ctx.currentRegion = ctx.matchCurrentItem(filter.region, ctx.regionPersistedItems);
                
            }
            else {
                ctx.regionPlaceHolder = "Search Region";
            }

            if (filter.country != null && filter.country != undefined) {
                var countryName = ctx.matchIdStringToNameForDataCollection(filter.country, ctx.countryPersistedItems);
                ctx.currentCountry = ctx.matchCurrentItem(filter.country, ctx.countryPersistedItems);
               
            }
            else {
                ctx.countryPlaceHolder = "Search Country";
            }

            if (filter.companyType != null && filter.companyType != undefined) {
                ctx.companyTypeModel = EnumValues.flagsToList(CompanyTypeEnum, filter.companyType).map(function (item) { return { id: item }; });
                ctx.currentCompanyType = filter.companyType;              
            }
            else {
                ctx.companyTypePlaceHolder = "Search Company Type";
            }

            ctx.weightMatrixId = filter.weightMatrixId ? filter.weightMatrixId : '';
            ctx.referenceUniverseId = filter.referenceUniverseId ? filter.referenceUniverseId : '';
            ctx.comparativeGroup = filter.comparativeGroup != null ? filter.comparativeGroup.toString() : '';
            ctx.companyTypePublicOrPrivate = filter.companyTypePublicOrPrivate != null ? filter.companyTypePublicOrPrivate.toString() : '';
            ctx.researchType = filter.researchType != null ? filter.researchType.toString() : '';
            ctx.exportType = filter.exportType != null ? filter.exportType.toString() : '';
        }
        //#endregion

        //#region set and load drop-downs

        public accountPortfolioSelected = () => {
            var ctx = this;
            ctx.showResults = false;
            //Pass fields to model object  

            if (ctx.currentFilter.selectedPortfolioUniverse["type"] !== PortfolioUniversesType.Universe) {
                ctx.currentFilter.portfolioId = ctx.currentFilter.selectedPortfolioUniverse.id;
                ctx.currentFilter.portfolioName = ctx.currentFilter.selectedPortfolioUniverse.name;

            } else {
                ctx.currentFilter.universeId = ctx.accountUniverseId;
                ctx.currentFilter.portfolioId = null;
                ctx.currentFilter.portfolioName = null;
            }
            //Pass fields to model object
       

            //Save filter after selection change triggered
            ctx.saveFilter().then(() => {
                ctx.resultOutputFilter.portfolioId = (ctx.currentFilter.selectedPortfolioUniverse["type"] !== PortfolioUniversesType.Universe)? ctx.currentFilter.id : null ;
                //this.runCriteria(this.currentFilter.id);
            });
        };

        public rootPeerGroupSelected = (criteriaPeerGroupId: string) => {
            var ctx = this;
            ctx.showResults = false;
             ctx.crtPeerGroupId = criteriaPeerGroupId;
             if (criteriaPeerGroupId == "") {
                 ctx.currentPeerGroup = undefined;
                 ctx.crtPeerGroupId = undefined;

                 ctx.peerGroupPlaceHolder = "Search Peer Group";
                 console.log("Peer Group Name: NONE; Peer Group Id: " + ctx.crtPeerGroupId); 
             }
             else {
                 console.log("Peer Group Name: " + ctx.currentPeerGroup.name + "; Peer Group Id: " + ctx.crtPeerGroupId); 
             }

             //Pass fields to model object
             ctx.currentFilter.peerGroup = ctx.crtPeerGroupId;           
             ctx.currentFilter.peerGroupName = ctx.currentPeerGroup ? ctx.currentPeerGroup.name : null;
             
             //Save filter after selection change triggered
             ctx.saveFilter().then(() => {
                // this.runCriteria(this.currentFilter.id);
             });

        };

        public regionSelected = (criteriaRegionId: string) => {
             var ctx = this;
             ctx.regionId = criteriaRegionId;
             ctx.showResults = false;
             if (criteriaRegionId == "") {
                 ctx.currentRegion = undefined;
                 ctx.regionId = undefined;

                 ctx.regionPlaceHolder = "Search Region";
                 console.log("Region Name: NONE; Region Id: " + ctx.regionId);
             }
             else {
                 console.log("Region Name: " + ctx.currentRegion.name + "; Region Id: " + ctx.regionId);
             }

             //Pass fields to model object
             ctx.currentFilter.region = ctx.regionId;
             ctx.currentFilter.regionName = ctx.currentRegion? ctx.currentRegion.name: null;

             //Save filter after selection change triggered
             ctx.saveFilter().then(() => {
               //  this.runCriteria(this.currentFilter.id);
             });

        };

        public countrySelected = (criteriaCountryId: string) => {
            var ctx = this;
            ctx.showResults = false;
            ctx.countryId = criteriaCountryId;
            if (criteriaCountryId == "") {
                ctx.currentCountry = undefined;
                ctx.countryId = undefined;

                ctx.countryPlaceHolder = "Search Country";
                console.log("Country Name: NONE; Country Id: " + ctx.countryId); 
            }
            else {
                console.log("Country Name: " + ctx.currentCountry.name + "; Country Id: " + ctx.countryId); 
            }

            //Pass fields to model object
            ctx.currentFilter.country = ctx.countryId;          
            ctx.currentFilter.countryName = ctx.currentCountry ? ctx.currentCountry.name : null;
          
            //Save filter after selection change triggered
            ctx.saveFilter().then(() => {
               // this.runCriteria(this.currentFilter.id);
            });

        };

        public companyTypeSelected = (criteriaCompanyTypeId: number) => {
            var ctx = this;
            ctx.showResults = false;
            ctx.companyTypeId = criteriaCompanyTypeId;
            if (criteriaCompanyTypeId == 0) {
                ctx.currentCompanyType = undefined;
                ctx.companyTypeId = undefined;

                ctx.companyTypePlaceHolder = "Search Company Type";
                console.log("Company Type Name: NONE; Company Type Id: " + ctx.companyTypeId); 
            }
            else {
                console.log("Company Type Name: " + ctx.currentCompanyType.name + "; Company Type Id: " + ctx.companyTypeId); 
            }
            //Pass fields to model object
            ctx.currentFilter.companyType = ctx.companyTypeId;

            //Save filter after selection change triggered
            ctx.saveFilter().then(() => {
             //   this.runCriteria(this.currentFilter.id);
            });

        };        

        public selectCompanyType = (selectedCompanyType) => {
            var ctx = this;
            ctx.showResults = false;
            if (ctx.currentCompanyType != selectedCompanyType) {
                ctx.currentCompanyType = selectedCompanyType;
                ctx.companyTypeId = selectedCompanyType.intId;                              

                //Pass fields to model object
                ctx.currentFilter.companyType = ctx.companyTypeId;               
                
                console.log("Company Type Name: " + ctx.currentCompanyType.name + "; Company Type Id: " + ctx.companyTypeId); 

                //Save filter after selection change triggered
                ctx.saveFilter().then(() => {
                 //   this.runCriteria(this.currentFilter.id);
                });

            }
        };

        public selectCountry = (selectedCountry) => {
            var ctx = this;
            ctx.showResults = false;
            if (ctx.currentCountry != selectedCountry) {
                ctx.currentCountry = selectedCountry;
                ctx.countryId = selectedCountry.id;
               
                //Pass fields to model object
                ctx.currentFilter.country = ctx.countryId;    
                ctx.currentFilter.countryName = ctx.currentCountry.name;

                console.log("Country Name: " + ctx.currentCountry.name + "; Country Id: " + ctx.countryId); 

                //Save filter after selection change triggered
                ctx.saveFilter().then(() => {
                //    this.runCriteria(this.currentFilter.id);
                });

            }
        };

        public selectPeerGroup = (selectedPeerGroup) => {
            var ctx = this;
            ctx.showResults = false;
            if (ctx.currentPeerGroup != selectedPeerGroup) {
                ctx.currentPeerGroup = selectedPeerGroup;
                ctx.crtPeerGroupId = selectedPeerGroup.id;    
                                         
                //Pass fields to model object
                ctx.currentFilter.peerGroup = ctx.crtPeerGroupId;
                ctx.currentFilter.peerGroupName = ctx.currentPeerGroup.name;                
                
                console.log("Peer Group Name: " + ctx.currentPeerGroup.name + "; Peer Group Id: " + ctx.crtPeerGroupId); 
                
                //Save filter after selection change triggered
                ctx.saveFilter().then(() => {
                //    this.runCriteria(this.currentFilter.id);
                });

            }
        };

        public selectRegion = (selectedRegion) => {
            var ctx = this;
            ctx.showResults = false;
            if (ctx.currentRegion != selectedRegion) {
                ctx.currentRegion = selectedRegion;
                ctx.regionId = selectedRegion.id;

                //Pass fields to model object
                ctx.currentFilter.region = ctx.regionId;                  
                ctx.currentFilter.regionName = ctx.currentRegion.name;
                
                console.log("Region Name: " + ctx.currentRegion.name + "; Region Id: " + ctx.regionId);

                //Save filter after selection change triggered
                ctx.saveFilter().then(() => {
                  //  this.runCriteria(this.currentFilter.id);
                });
          
            }
        };

        deletedPortfolioOrUniverse() {
            this.showResults = false;
            this.currentFilter.universeId = null;
            this.currentFilter.universeName = null;
            this.currentFilter.portfolioId = null;
            this.currentFilter.portfolioName = null;
            this.saveFilter();
        }

        selectPortfolioOrUniverse = (item) => {
            var ctx = this;
            ctx.showResults = false;


            if (ctx.currentFilter.selectedPortfolioUniverse.id != item.id) {

                //Pass fields to model object
                ctx.currentFilter.selectedPortfolioUniverse = item;
                if (ctx.currentFilter.selectedPortfolioUniverse.type != PortfolioUniversesType.Universe) {
                    ctx.currentFilter.portfolioId = ctx.currentFilter.selectedPortfolioUniverse.id;
                    ctx.currentFilter.portfolioName = ctx.currentFilter.selectedPortfolioUniverse.name;
                    ctx.currentFilter.universeId = null;
                    ctx.currentFilter.universeName = null;
                } else {
                    ctx.currentFilter.universeId = ctx.currentFilter.selectedPortfolioUniverse.id;
                    ctx.currentFilter.universeName = ctx.currentFilter.selectedPortfolioUniverse.name;
                    ctx.currentFilter.portfolioId =null;
                    ctx.currentFilter.portfolioName = null;
                }
                console.log("selected portfolio or universe: " + ctx.currentFilter.selectedPortfolioUniverse.name + "; Id: " + ctx.currentFilter.selectedPortfolioUniverse.id + " ;type="+ ctx.currentFilter.selectedPortfolioUniverse.type);

                //Save filter after selection change triggered
                ctx.saveFilter();

            }
           
        };
        //#endregion

        private loadFilter(): ng.IPromise<FilterDto> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;

            // get filter ID
            var filterId: string = ctx.$routeParams['filterId'];

            //return Filter with FilterCriteria
            var getPromise: ng.IPromise<FilterDto> = ctx.FilterService.getFullFilterById(filterId, ctx.accountId, ctx.userId);

            getPromise.then((filter: FilterDto) => {
                this.currentFilter = filter;
                this.currentFilter.selectedPortfolioUniverse = filter.universeId !== 0 ? { 'id': filter.portfolioId } : { 'id': filter.universeId };          
                this.resultOutputFilter.filterId = filter.id;
                this.resultOutputFilter.portfolioId = filter.portfolioId;
                this.$rootScope['loading'] = false;
            });

            return getPromise;
        }

        //#region display result output

        public filterResultOutput(criteria)
        {
            var predefinedCols: any = { 'Company': true, 'Client ID': true, 'Company ID': true, 'Company name': true };
            return !predefinedCols[criteria.name];
        }

        public getCriteriaClassName(isValid)
        {
            if (isValid == null) {
                return null;
            }
            else {
                return isValid ? 'screening-criteria-valid' : 'screening-criteria-invalid';
            }
        }

        public isCriteriaValid(criteria)
        {
            return criteria.isValid;
        }

        public isNamedCriteriaValid(name, companyCriterias)
        {
            var ctx = this;
            var isValid = true;

            $(companyCriterias).filter(function () { return this.name == name; }).each(function () {
                var criteria = this;
                isValid = ctx.isCriteriaValid(criteria);
            });

            return isValid;
        }

        //#endregion

        public matchCurrentItem(idM: any, items: any): any {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].id === idM)
                        return items[i];
                }
            }

            return "";
        }

        public matchCurrentItemUniverse(idM: any, items: any): any {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].universeId === idM)
                        return items[i];
                }
            }

            return "";
        }

        public matchCurrentIntIdItem(idM: any, items: any): any {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].intId === idM)
                        return items[i];
                }
            }

            return "";
        }
        
        public matchIdStringToNameForDataCollection(idM: any, items: any): string {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].id === idM)
                        return items[i].name;
                }
            }

            return "";
        }
               
        public matchIntIdEnumToNameForDataCollection(idM: any, items: any): string {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].intId === idM)
                        return items[i].name;
                }
            }

            return "";
        }

        public matchIdNumberToNameForDataCollection(idM: any, items: any): string {
            var ctx = this;
            if (items != undefined && items != null && items.length > 0) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].universeId === idM)
                        return items[i].name;
                }
            }
            return "";
        }    

        public openSavePortfolio = function () {
            var ctx = this;
            ctx.operationsPopupId = "";
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/Portfolio/savePortfolioScreeningDialog.tpl.html',
                    controller: 'PortfolioAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        filterId: () => this.currentFilter.id
                    }
                });

            modalInstance.result.then((item) => {
            });
        };

        public editFilterName() {
            var ctx = this;
            if (ctx.currentFilter.isCurrentUserOwner || ctx.isAdmin) {
                ctx.newNameFilter = ctx.currentFilter.name;
                ctx.isRenamingFilterName = true;
            }
        }

        public saveFilterName() {
            var ctx = this;
            var def = ctx.$q.defer();

            var oldName = ctx.currentFilter.name;
            ctx.currentFilter.name = ctx.newNameFilter;
            var promise = ctx.saveFilter();
            promise
                .then(function () {
                    ctx.isRenamingFilterName = false;
                    def.resolve();
                })
                .catch(function () {
                    ctx.currentFilter.name = oldName;
                    def.reject();
                });
            return def.promise;
        }

        public cancelSaveFilterName() {
            var ctx = this;
            ctx.isRenamingFilterName = false;
        }

        public switchStandardState() {
            var ctx = this;
            if (ctx.currentFilter.type === FilterType.Private) {
                ctx.currentFilter.type = FilterType.Standard;
            }
            else {
                ctx.currentFilter.type = FilterType.Private;
            }
            ctx.saveFilter();
        }

        public saveFilter() {
            var ctx = this;

            if (ctx.weightMatrixId) {

                var findMatrixName = ctx.weightMatrices.filter(function (item) {
                    return (item.id === ctx.weightMatrixId);
                });

                if (findMatrixName) {
                    ctx.currentFilter.weightMatrixId = ctx.weightMatrixId;
                    ctx.currentFilter.weightMatrixName = findMatrixName[0].name;
                }
            } else {
                ctx.currentFilter.weightMatrixId = null;
                ctx.currentFilter.weightMatrixName = null;
            }

            if (ctx.referenceUniverseId) {

                var findRefUniv = ctx.referenceUniverses.filter(function (item) {
                    return (item.id === ctx.referenceUniverseId);
                });

                if (findRefUniv) {
                    ctx.currentFilter.referenceUniverseId = ctx.referenceUniverseId;
                    ctx.currentFilter.referenceUniverseName = findRefUniv[0].name;
                }
            } else {
                ctx.currentFilter.referenceUniverseId = null;
                ctx.currentFilter.referenceUniverseName = null;
            }

            ctx.currentFilter.comparativeGroup = (ctx.comparativeGroup) ? ComparativeGroupEnum[ctx.comparativeGroup] : null;
            ctx.currentFilter.companyTypePublicOrPrivate = ctx.companyTypePublicOrPrivate ? Number(ctx.companyTypePublicOrPrivate) : null;
            ctx.currentFilter.researchType = ctx.researchType ? Number(ctx.researchType) : null;
            ctx.currentFilter.exportType = ctx.exportType ? (ctx.exportType === ExportType.Excel.toString() ? ExportType.Excel : ExportType.CSV) : ExportType.Excel;

            var promise = ctx.FilterService.editFilter(ctx.currentFilter);

            promise.then(() => {
                this.$rootScope['loading'] = false;
                this.notificationFactory.success(this.currentFilter.name + ' saved successfully.');
            },
            (reason) => {
                ctx.notificationFactory.error('Error saving ' + ctx.currentFilter.name + '.', reason.data.message);
            });

            return promise;
        }

        public updateFilterCriteriaOrder() {
            var ctx = this;
            var criteriaIds: Array<string> = [];

            ctx.resultOutputPaged.items[0].criteria.forEach((item: CriteriaResultOutput) => {
                criteriaIds.push(item.filterCriteriaId);
            });

            ctx.FilterService.updateSelectedCriteriaOrderNumber(ctx.currentFilter.id, criteriaIds)
                .then(() => {
                    ctx.notificationFactory.success('Criteria order updated successfully.');
                    //ctx.runCurrentCriteria();
                    ctx.FilterCriteriaService.addFilterCriteriaToFilter(ctx.currentFilter.id, []).then(a => {
                        ctx.showResults = false;
                        ctx.getResultOutput(0);
                    });
                },
                (reason) => {
                    ctx.notificationFactory.error('Error updating filter criteria order.', reason.data.message);
                });

        }

        public openPopupForCriteria(filterCriteriaId: string) {
            var ctx = this;
            ctx.operationsPopupId = "";

            var modalInstanceSubscribe = ctx.$modal.open({
                templateUrl: 'Views/Tools/ScreeningTool/FilterCriteria/editCriteriaDialog.tpl.html',
                controller: 'EditFilterCriteriaController',
                //windowClass: 'app-modal-window',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    filterId: function () {
                        return ctx.$routeParams['filterId'];
                    },
                    filterCriteriaId: function () {
                        return filterCriteriaId;
                    },
                    isReport: function () {
                        return ctx.currentFilter.targetType;
                    }
                }
            });

            modalInstanceSubscribe.result.then((out) => {
                if (out["refresh"]) {
                    console.log("runCurrentCriteria");
                    //ctx.isModalOpen = false;
                    //ctx.refreshOutput = true;
                   // ctx.runCurrentCriteria();
                    if (!filterCriteriaId) {
                        ctx.getResultOutput(1);
                        ctx.showResults = false;
                    } else {
                        ctx.showResults = false;
                        ctx.FilterCriteriaService.addFilterCriteriaToFilter(ctx.currentFilter.id, []).then(a => {
                            ctx.getResultOutput(0);
                        });
                    }
                }
            });

            //ctx.isModalOpen = true;
        }

        public setOperationsPopupId(filterCriteriaId: string) {
            var ctx = this;
            ctx.operationsPopupId = (filterCriteriaId != ctx.operationsPopupId) ? filterCriteriaId : "";
        }

        public runCurrentCriteria() {
            var ctx = this;

            ctx.$rootScope["loading"] = true;

            var promise = ctx.runCriteria(ctx.currentFilter.id);
            promise.then(function () {
                ctx.notificationFactory.success("All criteria processed");
                ctx.$rootScope["loading"] = false;
            });

            return promise;
        }

        public runCriteria(filterId: string) {
            var ctx = this;
            var def = ctx.$q.defer();
            
            ctx.$rootScope['loading'] = true;
            //ctx.showNoData = false;
            var promise = undefined;
            var _portfolioId: string = ctx.currentFilter.portfolioId;
            var _universeId: number = ctx.currentFilter.universeId;
            var _report: boolean = false;
            var _refreshOutput = ctx.refreshOutput;
            if (ctx.currentFilter.targetType === 1) {
                _report = true;
            } else {
                _report = false;
            }

            promise = ctx.screeningToolFactory.runSelectedCriteria(filterId, _portfolioId, _universeId, _report, _refreshOutput);
            promise.then(() => {
                //alert(2);
                // reset order criteria

                /*
                // filter
                if (ctx.currentFilter.targetType === 0) {
                    ctx.resultOutputFilter.isValid = 4; // this will trigger ctx.getResultOutput(1)
                    ctx.resultOutputFilter.isValidEnabled = true;
                    ctx.resultOutputFilter.isNotValidEnabled = true;
                    ctx.resultOutputFilter.isNAEnabled = true;
                    ctx.resultOutputOrderBy = "CompanyNameLowerCase";
                    ctx.resultOutputOrderByAscending = true;
                }

                // report
                if (ctx.currentFilter.targetType === 1) {
                    // isValid is always -1 for a report (mongo ResultOutput.IsValid = -1)
                    ctx.resultOutputFilter.isValid = -1; // this will trigger ctx.getResultOutput(1)
                    ctx.resultOutputFilter.isValidEnabled = true;
                    ctx.resultOutputFilter.isNotValidEnabled = true;
                    ctx.resultOutputFilter.isNAEnabled = true;
                    ctx.resultOutputOrderBy = "CompanyNameLowerCase";
                    ctx.resultOutputOrderByAscending = true;
                }
                */
                ctx.getResultOutput(1)
                    .then(function () {
                    ctx.$rootScope['loading'] = false;
                    ctx.showResults = true;
                    ctx.showNoData = false;
                    if (ctx.resultOutputPaged.items.length === 1) {
                        if (!ctx.resultOutputPaged.items[0].companyName) {
                            ctx.showNoData = true;
                            console.log("The show no data is "+ctx.showNoData);
                        }
                    }
                    def.resolve();
                })
                ['catch'](function () {
                    ctx.$rootScope['loading'] = false;
                    ctx.showResults = true;
                    ctx.showNoData = false;
                    if (ctx.resultOutputPaged.items.length === 1) {
                        if (!ctx.resultOutputPaged.items[0].companyName) {
                            ctx.showNoData = true;
                        }
                    }
                    def.reject();
                });
            });
            promise.error((data, status, headers, config) => {
                ctx.notificationFactory.error("Error", ctx.staticObjects.getErrorMesageByStatusCode(status, data));
                def.reject();
            });
            
            return def.promise;
        }


        //get ResultOutput with paging
        public getResultOutput(pageIndex?: number, pageSize?: number): ng.IPromise<{}> {
            var ctx = this;
            ctx.$rootScope["loading"] = true;
            var def = ctx.$q.defer();

            // get pager
            var pager: Sustainalytics.Pager.PagerController = ctx.$scope['pager'];

            // If pager is not defined then abort execution.
            // Current controller is created before Pager controller.
            if (!pager) {
                ctx.$rootScope["loading"] = false;
                return;
            }

            if (pageIndex) {
                pager.pagingOptions.pageIndex = pageIndex;
            }

            if (pageSize) {
                pager.pagingOptions.pageSize = pageSize;
            }

            if (ctx.resultOutputFilter.filterId != null) {

                var skip = pager.pagingOptions.pageSize * (pager.pagingOptions.pageIndex - 1);
                var take = pager.pagingOptions.pageSize;

                ctx.resultOutputFilter.portfolioId = ctx.currentFilter.portfolioId;

                ctx.screeningToolFactory.getResultOutput(ctx.resultOutputFilter, skip, take, ctx.resultOutputOrderBy, ctx.resultOutputOrderByAscending)
                    .success((result: GetRunResultDto) => {
                    //alert(3);
                    var resultOutputPaged = new Sustainalytics.Common.PagedList<ResultOutput>();

                    resultOutputPaged.items = result.items;
                    resultOutputPaged.pagingOptions = pager.pagingOptions;
                    resultOutputPaged.totalItemsCount = result.count;
                    resultOutputPaged.totalPageCount = Math.ceil(result.count / pager.pagingOptions.pageSize);

                    ctx.resultOutputPaged = resultOutputPaged;
                    pager.totalItemsCount = result.count;

                    def.resolve();
                    ctx.$rootScope["loading"] = false;
                }).error((data, status, headers, config, statusText) => {
                    ctx.$rootScope["loading"] = false;
                    ctx.notificationFactory.error("Error", ctx.staticObjects.getErrorMesageByStatusCode(status, data));

                    def.reject();
                });
            }
            else {
                ctx.$rootScope["loading"] = false;
                def.reject();
            }

            return def.promise;
        }

        public toggleResultOutputOrder(orderBy) {
            var ctx = this;
            var currentOrderBy = ctx.resultOutputOrderBy;

            if (orderBy === currentOrderBy) {
                ctx.resultOutputOrderByAscending = !ctx.resultOutputOrderByAscending;
            }
            else {
                ctx.resultOutputOrderBy = orderBy;
                ctx.resultOutputOrderByAscending = true;
            }
        }

        public computeResultOutputFilterIsValid() {
            var ctx = this;
            var filter = ctx.resultOutputFilter;
            var isValid = null;

            if (filter.isValidEnabled && filter.isNotValidEnabled && !filter.isNAEnabled) {
                isValid = 4;
            }
            else {
                if (filter.isValidEnabled) {
                    isValid = 1;
                }
                else {
                    if (filter.isNotValidEnabled) {
                        isValid = 0;
                    }
                    else {
                        if ((filter.isNAEnabled)) {
                            isValid = -1;
                        }
                    }
                }
            }

            if (filter.isValidEnabled && filter.isNAEnabled && !filter.isNotValidEnabled) {
                isValid = 2;
            }

            if (filter.isNotValidEnabled && filter.isNAEnabled && !filter.isValidEnabled) {
                isValid = 3;
            }

            if (filter.isNotValidEnabled && filter.isNAEnabled && filter.isValidEnabled) {
                isValid = null;
            }
            ctx.resultOutputFilter.isValid = isValid;
        }

        // search for company assessments when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                if (ctx.currentFilter) {
                    ctx.getResultOutput();
                }    
            });
        }

        public goBack(targetType: TargetType) {
            var ctx = this;
            var strTargetType = "";
            if (targetType === TargetType.Screening) {
                strTargetType = "screening";
            } else {
                strTargetType = "report";
            }

            ctx.$location.url('/tools/' + strTargetType);
        }

        public publishUnpublishStandardFilter() {


            var ctx = this;

            var standardFilter = new FilterDto();

            if (ctx.currentFilter.type === FilterType.Private || ctx.currentFilter.type === FilterType.Shared) {

                
                for (var prop in ctx.currentFilter) {
                    standardFilter[prop] = ctx.currentFilter[prop];
                }

                standardFilter.name = ctx.currentFilter.name + " (standard)";
                standardFilter.type = FilterType.Standard;
                standardFilter.targetType = ctx.currentFilter.targetType;
                standardFilter.status = FilterStatus.Draft;
                standardFilter.publishDate = moment().toDate();
                standardFilter.unPublishDate = null;

                var promise = ctx.FilterService.saveFilter(standardFilter);
                promise.then((filter: FilterDto) => {
                    ctx.notificationFactory.success('Standard filter scheduled successfully.');
                },
                    (reason) => {
                        ctx.notificationFactory.error('Error creating standard filter.', reason.data.message);
                    });
            }
            else if (ctx.currentFilter.type == FilterType.Standard) 
            {
                ctx.currentFilter.unPublishDate = moment().toDate();
                ctx.currentFilter.status = FilterStatus.Draft;

                var promise = ctx.FilterService.saveFilter(ctx.currentFilter);
                promise.then((filter: FilterDto) => {
                    ctx.notificationFactory.success('Standard filter removed successfullly.');
                },
                    (reason) => {
                        ctx.notificationFactory.error('Error creating standard filter.', reason.data.message);
                    });

            }

        }

        public generateReport() {
            var ctx = this;

            // call LRTM task
            var taskNumber = ctx.currentFilter.exportType === ExportType.Excel ? 100 : 101;

            var reportType = "";
            var filterMatrix = "";
            var filterComparativeGroup = "";
            var eventAction = "";

            if (ctx.currentFilter.targetType === TargetType.Screening) {
                var screeningPromise = ctx.LongRunningTaskManagerService.runTask(ctx.currentFilter.name + '_' + moment().format("DDMMYYYY"), ctx.currentFilter.id, taskNumber, true, null);

                if (ctx.currentFilter.type === FilterType.Standard) {
                    reportType = "Screening tool - system filters";
                    eventAction = ExportType[ctx.currentFilter.exportType] + ctx.currentFilter.name;
                } else {
                    reportType = "Screening tool - custom filters";
                    eventAction = ExportType[ctx.currentFilter.exportType] + "CustomFilter";
                }
            }

            if (ctx.currentFilter.targetType === TargetType.Report) {
                var reportPromise = ctx.LongRunningTaskManagerService.runTask(ctx.currentFilter.name + '_' + moment().format("DDMMYYYY"), ctx.currentFilter.id, taskNumber, true, null);

                if (ctx.currentFilter.type === FilterType.Standard) {
                    reportType = "Reporting tool - system reports";
                    eventAction = ExportType[ctx.currentFilter.exportType] + ctx.currentFilter.name;
                } else {
                    reportType = "Reporting tool - custom reports";

                    eventAction = ExportType[ctx.currentFilter.exportType] + "CustomReport";
                    filterMatrix = ctx.currentFilter.weightMatrixName;
                    filterComparativeGroup = ComparativeGroupEnum[ctx.currentFilter.comparativeGroup];
                }
            }

            if (reportType !== '') {
                ga('create', 'UA-4379897-6', {
                    'userId': ctx.userId,
                    'cookieDomain': 'none',
                    'name': 'globalAccess'
                });

                ga('globalAccess.set', 'dimension1', ctx.userId);

                var dateNow = new Date();
                var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                var gaObject: any = {
                    Date: dateNowString,
                    AccountId: ctx.accountId,
                    UserId: ctx.userId
                };

                if (reportType === "Reporting tool - custom reports") {
                    gaObject.Matrix = filterMatrix;
                    if (!isNaN(parseInt(filterComparativeGroup)))
                        filterComparativeGroup = ComparativeGroupEnum[filterComparativeGroup];

                    gaObject.ComparativeGroup = filterComparativeGroup;
                }

                ga('globalAccess.send', {
                    'hitType': 'event',
                    'eventCategory': reportType,
                    'eventAction': eventAction,
                    'eventLabel': JSON.stringify(gaObject)
                });
            }
        }

        public returnCssClassByTargetType(targetType: TargetType) : string {
            var ctx = this;
            var value = "";

            if (targetType === TargetType.Screening && !ctx.currentFilter.portfolioId)
                value = "screening-no-portfolio";

            if (targetType === TargetType.Screening && ctx.currentFilter.portfolioId)
                value = "screening-with-portfolio";

            if (targetType === TargetType.Report && !ctx.currentFilter.portfolioId)
                value = "reporting-no-portfolio";

            if (targetType === TargetType.Report && ctx.currentFilter.portfolioId)
                value = "reporting-with-portfolio";

            return value;
        }

        //check if current criteria allows Editing (for reports you shouldn't allow editing -both admin and client)
        //(for screening you should allow editing for admin)
        //(for screening you should allow editing in client if the filter is yours)
        //(if you have a data point that has no filterCriteriaGroup you shouldn't be able to edit it - only to delete it) 
        public allowEditFilterCriteria(criteria: CriteriaResultOutput) {
            var ctx = this;

            if (criteria.companiesCount === "Data Point") {
                return false;
            } else if (ctx.currentFilter.isCurrentUserOwner && ctx.currentFilter.type !== 2 && ctx.currentFilter.targetType !== 1) {
                return true;
            } else if (ctx.isAdmin && ctx.currentFilter.targetType !== 1) {
                return true;
            }
            return false;
        }

        public newNameFilterHasInvalidCharacters() {
            if (!this.newNameFilter) {
                return false;
            }

            var invalidCharacters = ['\\', '/', ':', '*', '?', '"', '<', '>', '|'];
            return invalidCharacters.some(x => this.newNameFilter.indexOf(x) >= 0);
        }
    }

    angular.module(screeningToolModuleName).controller('EditFilterController',
           ['$rootScope',
            '$scope',
            '$q',
            '$location',
            'RoutingService',
            'FilterService',
            'FilterCriteriaService',
            'screeningToolFactory',
            'PortfolioService',
            'PortfolioSearchService',
            'notificationFactory',
            'WeightMatricesService',
            'ReferenceUniversesService',
            'staticObjects',
            '$modal',
            'LongRunningTaskManagerService',
            EditFilterController]);

}